<template>
  <div class="chart-container">
    <h2 v-if="title">{{ title }}</h2>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
// 添加 ESLint 注释告诉它 defineProps 是可用的(要保留，不保留就报错)
/* eslint-disable no-undef */
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
import request from '@/utils/request';

// 定义props
const props = defineProps({
  title: {
    type: String,
    default: '商品销量统计'
  },
  showLabel: {
    type: Boolean,
    default: true
  },
});

// 获取DOM引用
const chartRef = ref(null);
let chartInstance = null;
const chartData = ref({
  xData: [],
  seriesData: []
});
const loading = ref(false);

// 获取图表数据
const fetchChartData = async () => {
  loading.value = true;
  try {
    const res = await request({
      url: '/api/income/chart',
      method: 'get'
    });
    
    if (res.code === '200' && res.data) {
      // 处理API返回的数据
      const sortedData = res.data.categoryIncomes.sort((a, b) => b.categoryIncome - a.categoryIncome);
      chartData.value.xData = sortedData.map(item => item.categoryName);
      chartData.value.seriesData = sortedData.map(item => item.categoryIncome);
    }
  } catch (error) {
    console.error('获取收入数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    // 如果已有实例则先销毁
    if (chartInstance) {
      chartInstance.dispose();
    }
    
    chartInstance = echarts.init(chartRef.value);
    updateChart();
    
    // 响应式调整大小
    window.addEventListener('resize', resizeChart);
  }
};

// 更新图表配置
const updateChart = () => {
  if (chartInstance) {
    const option = {
      title: {
        text: props.title,
        left: 'center',
        subtext: `总收入: ￥${chartData.value.seriesData.reduce((sum, num) => sum + num, 0).toFixed(2)}`,
        subtextStyle: {
          fontSize: 14,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: params => {
          const data = params[0];
          return `
            <div style="font-weight:bold">${data.name}</div>
            <div>收入: ￥${data.value.toFixed(2)}</div>
            <div>占比: ${((data.value / chartData.value.seriesData.reduce((sum, num) => sum + num, 0)) * 100).toFixed(2)}%</div>
          `;
        }
      },
      xAxis: {
        type: 'category',
        data: chartData.value.xData,
        axisLabel: {
          rotate: 30 // 如果标签太长可以旋转
        }
      },
      yAxis: {
        type: 'value',
        name: '收入(元)',
        axisLabel: {
          formatter: value => `￥${value}`
        }
      },
      series: [
        {
          type: 'bar',
          data: chartData.value.seriesData,
          itemStyle: {
            color: props.color,
            borderRadius: [4, 4, 0, 0]
          },
          label: {
            show: props.showLabel,
            position: 'top',
            formatter: params => `￥${params.value.toFixed(2)}`
          },
          barWidth: '60%',
        }
      ],
      grid: {
        containLabel: true,
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: props.title ? '20%' : '15%'
      }
    };
    
    chartInstance.setOption(option);
  }
};

// 调整图表大小
const resizeChart = () => {
  chartInstance?.resize();
};

// 组件挂载时初始化
onMounted(async () => {
  await fetchChartData();
  initChart();
});

// 监听props变化
watch(() => [props.color, props.showLabel], () => {
  updateChart();
});

// 监听数据变化
watch(chartData, () => {
  updateChart();
}, { deep: true });

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartInstance) {
    window.removeEventListener('resize', resizeChart);
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.chart-container h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.chart {
  width: 100%;
  height: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>